package com.kaikai.edu.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kaikai.commonutils.BaseConstant;
import com.kaikai.commonutils.BeanCopyUtils;
import com.kaikai.commonutils.R;
import com.kaikai.config.ChannelConstant;
import com.kaikai.edu.entity.EduEmail;
import com.kaikai.edu.entity.EduTeacher;
import com.kaikai.edu.entity.EduUser;
import com.kaikai.edu.entity.ao.EduEmailQueryAO;
import com.kaikai.edu.entity.ao.EduEmailSendAO;
import com.kaikai.edu.mapper.EduUserMapper;
import com.kaikai.edu.mapper.EmailMapper;
import com.kaikai.edu.service.EduEmailService;
import com.kaikai.edu.service.EduTeacherService;
import com.kaikai.edu.utils.MsgSender;
import com.kaikai.properties.SendMailProps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yujiankai
 * @since 2022-01-05
 */
@Service
public class EmailServiceImpl implements EduEmailService {

    @Autowired
    private SendMailProps property;

    @Autowired
    private EmailMapper emailMapper;

    @Autowired
    private EduTeacherService teacherService;

    @Autowired
    private EduUserMapper userMapper;

    @Autowired
    private MsgSender msgSender;

    @Override
    public R sendEmail(EduEmailSendAO eduEmailSendAO) {
        EduEmail eduEmail = new EduEmail();
        try {
            BeanCopyUtils.copy(eduEmailSendAO, eduEmail);
            eduEmail.setSendMailProps(property);
            eduEmail.setEduEmailId(UUID.randomUUID().toString());
            eduEmail.setSendTime(new Date());
            eduEmail.setSendRslt(BaseConstant.MSG_SEND_ING);
            emailMapper.insertEmailSendRec(eduEmail);
            //将消息推送到kafka
            msgSender.sendMessage(eduEmail, ChannelConstant.EMAIL_DEFAULT_CHANNEL);
            return R.ok().message("发送成功");
        } catch (Exception e) {
            eduEmail.setSendRslt(BaseConstant.MSG_SEND_ERROR);
            eduEmail.setSendFailReason(e.getMessage());
            emailMapper.updateEmailSendRec(eduEmail);
            e.printStackTrace();
            return R.error().message("发送失败");
        }

    }

    @Override
    public R queryEmailSendRecList(EduEmailQueryAO queryAO) {
        Page<EduEmailQueryAO> page = new Page<>(queryAO.getCurrentPage(), queryAO.getPageSize());
        IPage<EduEmail> emailIPage = emailMapper.getEmailSendRecList(page, queryAO);
        List<EduEmail> emailSendRecList = emailIPage.getRecords();
        //查询所有讲师
        List<EduTeacher> teacherList = teacherService.list(null);
        //查询所有用户
        List<EduUser> userList = userMapper.getUserList();
        //给返回信息添加讲师名称
        emailSendRecList.forEach(emailSendRec -> {
            //设置默认接收人名称为邮箱
            emailSendRec.setReceiverName(emailSendRec.getReceiver());
            List<String> receiverList = Arrays.asList(emailSendRec.getReceiver().split(","));
            StringBuilder receiverName = new StringBuilder();
            receiverList.forEach(receiver -> {
                teacherList.forEach(teacher -> {
                    if (Objects.equals(teacher.getEmail(), receiver)) {
                        receiverName.append(teacher.getName() + BaseConstant.COMMA);
                    }
                });
            });
            if(StringUtils.isNotEmpty(receiverName)&&!"-1".equals(receiverName.lastIndexOf(BaseConstant.COMMA))){
                receiverName.deleteCharAt(receiverName.lastIndexOf(BaseConstant.COMMA));
                emailSendRec.setReceiverName(receiverName.toString());
            }
            //设置发送人名称
            userList.forEach(user ->{
                if(Objects.equals(user.getUserId(),emailSendRec.getUserId())) {
                    emailSendRec.setSender(user.getNickName());
                }
            });
        });
        emailIPage.setRecords(emailSendRecList);
        return R.ok().data(emailIPage);
    }


    @Override
    public R resendEmail(String emailId) {
        EduEmail eduEmail = null;
        try {
            eduEmail = emailMapper.getEmailSendRecById(emailId);
            if (Objects.isNull(eduEmail)) {
                return R.error().message("该发送记录不存在");
            }
            eduEmail.setSendFailReason("");
            //重发次数+1
            eduEmail.setResendCount(eduEmail.getResendCount()+1);
            eduEmail.setSendMailProps(property);
            eduEmail.setSendTime(new Date());
            eduEmail.setSendRslt(BaseConstant.MSG_SEND_ING);
            emailMapper.updateEmailSendRec(eduEmail);
            //将消息推送到kafka
            msgSender.sendMessage(eduEmail, ChannelConstant.EMAIL_DEFAULT_CHANNEL);
            return R.ok().message("发送成功");
        } catch (Exception e) {
            eduEmail.setSendRslt(BaseConstant.MSG_SEND_ERROR);
            eduEmail.setSendFailReason(e.getMessage());
            emailMapper.updateEmailSendRec(eduEmail);
            e.printStackTrace();
            return R.error().message("发送失败");
        }

    }

    @Override
    public R getUserList() {
        try{
            List<EduUser> userList = userMapper.getUserList();
            return R.ok().data(userList);
        }catch(Exception e){
            e.printStackTrace();
            return R.error().message("查询用户失败");
        }
    }
}
